package top.hcode.hoj;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import org.nutz.lang.Strings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author orangej
 * @since 2025/2/21
 */
public class NumParseApp {
    public static void main(String[] args) {
        String file = "E:/objective-score.txt";
//        String file = "E:/time.txt";
        List<Integer> numList = FileUtil.readLines(file, "UTF-8").stream()
                .map(String::trim)
                .map(it -> StrUtil.subBefore(it, ".", true))
                .filter(Strings::isNotBlank)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        analyze(numList);
    }

    public static class NumParseResult {
        public int count;
        public int min;
        public int max;
        public double average;
        public List<RegionPercent> regionPercentList;
    }

    public static class RegionPercent {
        public int min;
        public int max;
        public double percent;
    }

    // 分析一组数字，给出数量、最小值、最大值、平均值，各区间分布占比
    public static NumParseResult analyze(List<Integer> numList) {
        NumParseResult result = new NumParseResult();
        if (numList == null || numList.isEmpty()) {
            return result;
        }

        int count = numList.size();
        int min = Collections.min(numList);
        int max = Collections.max(numList);
        double average = numList.stream().mapToInt(Integer::intValue).average().orElse(0.0);

        result.count = count;
        result.min = min;
        result.max = max;
        result.average = average;

        // 假设区间为 [0-10), [10-20), [20-30), ...
        int[] intervals = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        int[] distribution = new int[intervals.length];

        for (int num : numList) {
            for (int i = 0; i < intervals.length; i++) {
                if (num < intervals[i]) {
                    distribution[i]++;
                    break;
                }
            }
        }

        result.regionPercentList = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            double percentage = NumberUtil.div(distribution[i], count, 4) * 100;
            int start = i == 0 ? 0 : intervals[i - 1];

            RegionPercent regionPercent = new RegionPercent();
            regionPercent.min = start;
            regionPercent.max = intervals[i];
            regionPercent.percent = percentage;
            result.regionPercentList.add(regionPercent);
        }

        // 删除尾部percent为0的区间
        for (int i = result.regionPercentList.size() - 1; i >= 0; i--) {
            if (result.regionPercentList.get(i).percent == 0) {
                result.regionPercentList.remove(i);
            } else {
                break;
            }
        }

        return result;
    }
}